﻿using System;
using System.Collections.Generic;
using System.Windows.Controls;
using System.Windows.Interactivity;

namespace Wen.Core.Behaviors
{
	public class UniqueExpanderBehavior : Behavior<Expander>
	{
		private static readonly Dictionary<string, List<Expander>> Groups = new Dictionary<string, List<Expander>>();

		public string GroupName { private get; set; }

		protected override void OnAttached() {
			base.OnAttached();
			if (string.IsNullOrEmpty(GroupName))
				throw new ArgumentNullException();
			if (!Groups.ContainsKey(GroupName)) {
				Groups.Add(GroupName, new List<Expander>());
				AssociatedObject.IsExpanded = true;
			}
			Groups[GroupName].Add(AssociatedObject);
			AssociatedObject.Expanded += AssociatedObjectExpanded;
		}

		protected override void OnDetaching() {
			base.OnDetaching();
			AssociatedObject.Expanded -= AssociatedObjectExpanded;
		}

		void AssociatedObjectExpanded(object sender, System.Windows.RoutedEventArgs e) {
			Expander expander = sender as Expander;
			if (expander == null)
				return;
			foreach (Expander exp in Groups[GroupName]) {
				if (exp != expander)
					exp.IsExpanded = false;
			}
		}
	}
}
